class Solution
{
public:
    struct Trie
    {
        Trie *left;
        Trie *right;

        ~Trie()
        {
            delete left;
            delete right;
        }
    };

    int maximumStrongPairXor(vector<int> &nums)
    {
        sort(nums.begin(), nums.end());

        Trie temp;
        Trie *root = &temp;
        int ans = 0;
        int front = 0;
        int back = 0;
        for (; front < nums.size(); ++front)
        {
            int num = nums[front];
            // 将 小于等于 2 * num 的数插入到 Trie 中
            while (back < nums.size() && nums[back] <= 2 * num)
            {
                Trie *cur = root;
                for (int i = 21; i >= 0; --i)
                {
                    int bit = (nums[back] >> i) & 1;
                    if (bit == 0)
                    {
                        if (cur->left == nullptr)
                        {
                            cur->left = new Trie();
                        }
                        cur = cur->left;
                    }
                    else
                    {
                        if (cur->right == nullptr)
                        {
                            cur->right = new Trie();
                        }
                        cur = cur->right;
                    }
                }
                ++back;
            }

            // 在树上查找 num 的最大异或值
            Trie *cur = root;
            bool greater = false;
            int maxXor = 0;
            for (int i = 21; i >= 0; --i)
            {
                int bit = (num >> i) & 1;
                if (bit == 0)
                {
                    if (cur->right)
                    {
                        cur = cur->right;
                        maxXor |= (1 << i);
                        greater = true;
                    }
                    else
                    {
                        cur = cur->left;
                    }
                }
                else
                {
                    if (cur->left && greater)
                    {
                        cur = cur->left;
                        maxXor |= (1 << i);
                    }
                    else
                    {
                        cur = cur->right;
                    }
                }
            }
            ans = max(ans, maxXor);
        }
        return ans;
    }
};